package com.example.myblog.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class AiService {

    @Value("${ai.api-key:}")
    private String apiKey;

    @Value("${ai.base-url:https://api.openai.com/v1}")
    private String baseUrl;

    @Value("${ai.model:gpt-4o-mini}")
    private String model;

    private final RestTemplate restTemplate = new RestTemplate();

    public String chat(String userMessage, List<Map<String, String>> history) {
        if (apiKey == null || apiKey.isBlank()) {
            throw new IllegalStateException("AI 接口未配置：缺少 api-key");
        }

        String url = baseUrl.endsWith("/") ? baseUrl + "chat/completions" : baseUrl + "/chat/completions";

        // 组装 messages，包含系统提示 + 历史 + 当前用户消息
        List<Map<String, Object>> messages = new ArrayList<>();
        Map<String, Object> system = new HashMap<>();
        system.put("role", "system");
        system.put("content", "你是本博客的智能助手，使用简洁中文回答，必要时用 Markdown 有条理地解释。尽量结合用户问题的上下文，不要编造不存在的站点内容。");
        messages.add(system);

        if (history != null) {
            for (Map<String, String> m : history) {
                String role = m.getOrDefault("role", "user");
                String content = m.getOrDefault("content", "");
                if (content != null && !content.isBlank()) {
                    Map<String, Object> msg = new HashMap<>();
                    msg.put("role", role);
                    msg.put("content", content);
                    messages.add(msg);
                }
            }
        }

        Map<String, Object> user = new HashMap<>();
        user.put("role", "user");
        user.put("content", userMessage);
        messages.add(user);

        Map<String, Object> body = new HashMap<>();
        body.put("model", model);
        body.put("messages", messages);
        body.put("temperature", 0.7);
        body.put("max_tokens", 600);
        body.put("stream", false);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);

        try {
            Map<String, Object> resp = restTemplate.postForObject(url, entity, Map.class);
            if (resp == null) {
                throw new RuntimeException("AI 接口无响应");
            }
            Object choicesObj = resp.get("choices");
            if (!(choicesObj instanceof List<?> choices) || choices.isEmpty()) {
                throw new RuntimeException("AI 接口返回缺少choices");
            }
            Object first = choices.get(0);
            if (!(first instanceof Map<?, ?> choice)) {
                throw new RuntimeException("AI 返回结构异常");
            }
            Object messageObj = choice.get("message");
            if (!(messageObj instanceof Map<?, ?> messageMap)) {
                throw new RuntimeException("AI 返回消息缺失");
            }
            Object contentObj = messageMap.get("content");
            String content = contentObj == null ? null : contentObj.toString();
            if (content == null || content.isBlank()) {
                throw new RuntimeException("AI 回复为空");
            }
            return content;
        } catch (Exception e) {
            throw new RuntimeException("调用AI接口失败: " + e.getMessage(), e);
        }
    }
}